package com.histone.heartbeat.aop;

import com.histone.heartbeat.pojo.resp.ResultBean;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

@Aspect
@Component
@Slf4j
/**
 * 所有返回值是ResultBean的Controller  经由此aop
 */
public class ControllerAop {

    @Pointcut("execution(public com.histone.heartbeat.pojo.resp.ResultBean *(..))")
    public void result() {
    }

    @Around("result()")
    public Object handlerControllerMethod(ProceedingJoinPoint pjp) {
        long startTime = System.currentTimeMillis();

        ResultBean<?> result;

        MethodSignature signature = ((MethodSignature) pjp.getSignature());
        //获取方法参数名
        String[] paramNames = signature.getParameterNames();
        //获取参数值
        Object[] paramValues = pjp.getArgs();
        log.info("{} get params:::", pjp.getSignature());
        for (int i = 0; i < paramNames.length; i++) {
            log.info(paramNames[i] + "  ------  " + paramValues[i]);
        }
        try {
            result = (ResultBean<?>) pjp.proceed();
        } catch (Throwable e) {
            // 处理异常
            result = handlerException(pjp, e);
        }

        log.info("{} use time: {}, result is {}" , pjp.getSignature(), (System.currentTimeMillis() - startTime), result.toString());

        return result;
    }

    private ResultBean<?> handlerException(ProceedingJoinPoint pjp, Throwable e) {
        ResultBean.ErrorCode errorCode = ResultBean.ErrorCode.ERROR;
        String errMsg = "系统异常";

        // 已知异常
        if (e instanceof NullPointerException) {
            errMsg = "查询结果为空";
            errorCode = ResultBean.ErrorCode.NULL;
        }
        log.error(pjp.getSignature() + " error ", e.getMessage());

        return new ResultBean<>(errorCode, errMsg);
    }
}
